#pragma once

#include <pthread.h>

/////////////////////////////////////////////////
/// \class ThreadExecutor
///
/// \tparam Runnable the thread runnable type,
///         should implement the operation()() function
///
/// \brief Execute runnable in a new thread
///
/// Run the runnable in a new thread
/////////////////////////////////////////////////
template<typename Runnable>
	class ThreadExecutor
{
public:

	/// Create the thread executor,
	/// the runnable should implement the operation()() function
	ThreadExecutor(Runnable &runnable)
		: m_runnable(runnable)
	{
	}

	virtual ~ThreadExecutor()
	{
	}

	/// Start and run the runnable in a new thread
	int operator()()
	{
		pthread_t thread;
		return pthread_create(&thread, NULL, Start, this);
	}

private:

	/// The callback function for pthread, simply call the operation()() of the runnable.
	static void* Start(void* args)
	{
		ThreadExecutor<Runnable> *self = (ThreadExecutor<Runnable>*)args;
		self->m_runnable();
	}

	Runnable &m_runnable;	/// The runnable
};
